import {getToken, removeToken} from '@/utils/auth'
import {axiosAuth} from '@/utils/request'

const user = {
    state: {
        token: getToken(),
        id: '',
        name: '',
        avatar: '',
        roles: [],
        permissions: []
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_ID: (state, id) => {
            state.id = id
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        }
    },

    actions: {
        // 获取用户信息
        GetInfo({commit, state}) {
            return new Promise((resolve, reject) => {
                axiosAuth({
                    url: '/getInfo',
                    method: 'get'
                }).then(res => {
                    const data = res.data
                    const avatar = (data.avatar === "" || data.avatar == null) ? require("@/assets/images/profile.png") : data.avatar;
                    if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                        commit('SET_ROLES', data.roles)
                        commit('SET_PERMISSIONS', data.permissions)
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT'])
                    }
                    commit('SET_ID', data.userId)
                    commit('SET_NAME', data.userName)
                    commit('SET_AVATAR', avatar)
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出系统
        LogOut({commit, state}) {
            return new Promise((resolve, reject) => {
                axiosAuth({
                    url: '/logout',
                    method: 'post'
                }).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 登出
        FedLogOut({commit}) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user
